package com.joysuch.wwyt.api.service.impl;

import com.joysuch.wwyt.api.dataaccess.OrientationDataSyncService;
import com.joysuch.wwyt.api.service.AlarmReSubscribeService;
import com.joysuch.wwyt.api.service.ApiAlarmSubscribeService;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.config.RedisClient;
import com.joysuch.wwyt.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 叶君翔
 * @date 2023/07/25 19:53
 */
@Service
@Slf4j
public class AlarmReSubscribeServiceImpl implements AlarmReSubscribeService {

    @Autowired
    private ApiAlarmSubscribeService apiAlarmSubscribeService;

    @Autowired
    private OrientationDataSyncService orientationDataSyncService;

    @Autowired
    private RedisClient redisClient;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void cronResubscribeAlarm() {
        String value = redisClient.get(Constant.LOCATE_CONFIG_UPDATE);
        if (!StringUtil.isEmpty(value)) {
            String orgCode = "";
            String tenentId = "";
            try {
                String[] split = value.split("#");
                if (split.length == 2) {
                    orgCode = split[0];
                    tenentId = split[1];
                    this.reSubscribeAlarm(orgCode, Long.valueOf(tenentId));
                }
            } catch (Exception e) {
                log.error("reSubscribeApiAlarm fail, orgCode: {}, tenentId: {}, errMsg: {}", orgCode, tenentId, e.getMessage());
            } finally {
                redisClient.removeKey(Constant.LOCATE_CONFIG_UPDATE);
            }
        }
    }

    @Override
    @Transactional
    public void reSubscribeAlarm(String orgCode, Long tenentId) {
        log.info("========== 修改人员定位配置, 需要重新订阅服务, orgCode: {}, tenentId: {}", orgCode, tenentId);
        apiAlarmSubscribeService.updateStatus(orgCode, tenentId);
        orientationDataSyncService.batchApiV3Subscribe();
    }

}
